package org.penguin.study.bk.dict.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.penguin.study.bk.base.vo.DictModel;
import org.penguin.study.bk.base.vo.Result;
import org.penguin.study.bk.constant.CommonConstant;
import org.penguin.study.bk.dict.entity.SysDict;
import org.penguin.study.bk.dict.service.SysDictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author chengyinghua
 */
@Slf4j
@RestController
@RequestMapping("/sys/dict")
public class SysDictController {

    @Autowired
    private SysDictService sysDictService;

    /**
     * @param sysDict
     * @return
     * @功能：新增 如果Id重复，会报错: SQLIntegrityConstraintViolationException: Duplicate entry 'x' for key 'Primary',否则会用指定ID插入
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result<SysDict> add(@RequestBody SysDict sysDict) {
        Result<SysDict> result = new Result<>();
        try {
            sysDict.setCreatedTime(new Date());
            sysDict.setDeleted(CommonConstant.DEL_FLAG_0);
            sysDictService.save(sysDict);
            result.success("保存成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("保存失败");
        }
        return result;
    }

    /**
     * @param sysDict
     * @return
     * @功能：编辑
     */
    @RequestMapping(value = "/edit", method = RequestMethod.PUT)
    public Result<SysDict> edit(@RequestBody SysDict sysDict) {
        Result<SysDict> result = new Result<>();
        SysDict sysdict = sysDictService.getById(sysDict.getId());
        if (sysdict == null) {
            result.error500("未找到对应实体");
        } else {
            sysDict.setUpdatedTime(new Date());
            boolean ok = sysDictService.updateById(sysDict);
            if (ok) {
                result.success("编辑成功!");
            }
        }
        return result;
    }

    /**
     * 查询被删除的列表
     *
     * @return
     */
    @RequestMapping(value = "/deleteList", method = RequestMethod.GET)
    public Result<List<SysDict>> deleteList() {
        Result<List<SysDict>> result = new Result<>();
        List<SysDict> list = this.sysDictService.queryDeleteList();
        result.setSuccess(true);
        result.setResult(list);
        return result;
    }

    @RequestMapping(value = "/setDefault", method = RequestMethod.POST)
    public Result<?> setDefalut(@RequestBody SysDict sysDict) {
        if (StringUtils.isBlank(sysDict.getId())) {
            return Result.error("请选择记录!");
        }
        sysDictService.updateById(sysDict);
        return Result.ok("设置成功");
    }

    /**
     * 获取全部字典数据
     *
     * @return
     */
    @RequestMapping(value = "/queryAllDictItems", method = RequestMethod.GET)
    public Result<?> queryAllDictItems() {
        Map<String, List<DictModel>> res = sysDictService.queryAllDictItems();
        return Result.ok(res);
    }

    /**
     * 【接口签名验证】
     * 根据字典code加载字典text 返回
     *
     * @param dictCode
     * @return
     */
    @RequestMapping(value = "/loadDictItems/{dictCode}", method = RequestMethod.GET)
    public Result<List<DictModel>> loadDictItem(@PathVariable String dictCode) {
        Result<List<DictModel>> result = new Result<>();
        try {
            if (StringUtils.isNotEmpty(dictCode) && dictCode.length() > 3) {
                List<DictModel> dictItemList = sysDictService.queryDictItemsByCode(dictCode);
                result.setSuccess(true);
                result.setResult(dictItemList);
                log.info(result.toString());
            } else {
                result.error500("字典Code不正确！");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
            return result;
        }
        return result;
    }


    /**
     * 获取字典数据
     *
     * @param dictCode
     * @return
     */
    @RequestMapping(value = "/getDictText/{dictCode}/{key}", method = RequestMethod.GET)
    public Result<String> getDictText(@PathVariable("dictCode") String dictCode, @PathVariable("key") String key) {
        log.info(" dictCode : " + dictCode);
        Result<String> result = new Result<>();
        try {
            String text = sysDictService.queryDictTextByKey(dictCode, key);
            result.setSuccess(true);
            result.setResult(text);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
            return result;
        }
        return result;
    }
}
